import re
import uuid

from rest_framework import serializers

from apps.common.common_func import checkIdcard, value_is_in_arr
from apps.opoc.models import Opoc_InspectionRecord, Opoc_InspectionPhoto
from extensions.exceptions import ValidationError
from extensions.serializers import *
from apps.opoc.models import *


class Opoc_RecordsSerializer(BaseSerializer):
    company_name = CharField(source='company.name',  read_only=True, label='公司')
    labor_service_unit_name = CharField(source='labor_service_unit.name',  read_only=True, label='公司')
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    next_checker_name = CharField(source='next_checker.name',  read_only=True, label='下一步审核人')

    class Opoc_Certificate_ImgsSerializer(BaseSerializer):
        class Meta:
            model = Opoc_Certificate_Imgs
            fields = ['id', 'file','name','type']

    climb_high_img_item = Opoc_Certificate_ImgsSerializer(source='climb_high_img', read_only=True,label='登高证')
    electrician_img_item = Opoc_Certificate_ImgsSerializer(source='electrician_img', read_only=True,label='电工证')
    safety_officer_img_item = Opoc_Certificate_ImgsSerializer(source='safety_officer_img', read_only=True,label='安全员证')
    other_person_img_item = Opoc_Certificate_ImgsSerializer(source='other_person_img', read_only=True,label='其它证')

    class Common_PdfsSerializer(BaseSerializer):
        class Meta:
            model = Common_Pdfs
            fields = ['id', 'file','name']

    class Labor_service_unitsSerializer(BaseSerializer):
        class Meta:
            model = Labor_service_unit
            fields ="__all__"

    construction_contract_pdf_item = Common_PdfsSerializer(source='construction_contract_pdf', read_only=True, label='施工合同')
    insurance_pdf_item = Common_PdfsSerializer(source='insurance_pdf', read_only=True, label='保险')
    safety_responsibility_pdf_item = Common_PdfsSerializer(source='safety_responsibility_pdf', read_only=True, label='安全责任书')
    safety_education_pdf_item = Common_PdfsSerializer(source='safety_education_pdf', read_only=True, label='安全教育')
    safety_disclosure_pdf_item = Common_PdfsSerializer(source='safety_disclosure_pdf', read_only=True, label='安全交底')
    service_order_pdf_item = Common_PdfsSerializer(source='service_order_pdf', read_only=True, label='服务订单')
    task_dispatch_pdf_item = Common_PdfsSerializer(source='task_dispatch_pdf', read_only=True, label='任务单')
    labor_service_unit_items = Labor_service_unitsSerializer(source='labor_service_unit', read_only=True,many=True,label='任务单')
    class OpocChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')
        class Meta:
            model = OpocCheck
            fields = ['id', 'opoc','check_user','check_user_name','opinion','is_agree','add_time']

    opoc_checks_items = OpocChecksSerializer(
        source='check_records', many=True, read_only=True, label='审核记录')

    class Meta:
        model = Opoc_Records
        read_only_fields = ['id','company_name','opoc_checks_items','climb_high_img_item',
                            'labor_service_unit_name',
                            'next_checker_name',
                            'filled_by_name',
                            'electrician_img_item','safety_officer_img_item','other_person_img_item',
                            'construction_contract_pdf_item','insurance_pdf_item','safety_responsibility_pdf_item',
                            'safety_education_pdf_item','safety_disclosure_pdf_item','service_order_pdf_item',
                            'task_dispatch_pdf_item',
                            'labor_service_unit_items',
                            'add_time',
                            ]
        fields = ['id_number',
                  'name',
                  'phone',
                  'status',
                  'ascription',
                  'labor_service_unit',
                  'team_attribute',
                  'certificate_holding',
                  'contract_signing_begin_date',
                  'contract_signing_end_date',
                  'insurance_limit',
                  'insurance_effective_date',
                  'insurance_invalid_date',
                  'is_safety_responsibility',
                  'project_name',
                  'is_safety_education',
                  'is_monthly_safety_education',
                  'is_service_order',
                  'is_task_dispatch',
                  'is_safety_disclosure',
                  'other_conditions',
                  'climb_high_img',
                  'electrician_img',
                  'safety_officer_img',
                  'other_person_img',
                  'construction_contract_pdf',
                  'insurance_pdf',
                  'safety_responsibility_pdf',
                  'safety_education_pdf',
                  'safety_disclosure_pdf',
                  'service_order_pdf',
                  'task_dispatch_pdf',
                  'step',
                  'next_checker',
                  'is_effective',
                  'del_flag',
                  *read_only_fields]


    def validate_id_number(self, value):
        res =checkIdcard(value)
        if res!=True:
            raise ValidationError(value+"身份证号码格式不对")
        return value

    def validate_phone(self, value):
        print('self:',self)
        res = re.match(r'1[3,4,5,7,8,9]\d{9}', value)
        if re.match(r'1[3,4,5,7,8,9]\d{9}',value) is None:
            raise ValidationError(value + '手机号码格式不对')
        return value

    def validate(self, attrs):
        certificate_holding = attrs.get('certificate_holding')
        climb_high_img =attrs.get('climb_high_img')
        electrician_img =attrs.get('electrician_img')
        safety_officer_img =attrs.get('safety_officer_img')
        other_person_img =attrs.get('other_person_img')
        if 1 in certificate_holding:
            if not climb_high_img:
                raise ValidationError('请上传登高证')
        if 2 in certificate_holding:
            if not electrician_img:
                raise ValidationError('请上传电工证')
        if 3 in certificate_holding:
            if not safety_officer_img:
                raise ValidationError('请上传安全员证')
        if 4 in certificate_holding:
            if not other_person_img:
                raise ValidationError('请上传其它证')
        return attrs

    # def create(self, validated_data):
    #     return super().create(validated_data)
    #
    def update(self, instance, validated_data):
        print('validated_data:',validated_data)
        return super().update(instance, validated_data)


class Opoc_RecordsImportSerializer(BaseSerializer):
    # class Opoc_Labor_service_unitsSerializer(BaseSerializer):
    #     class Meta:
    #         model = Labor_service_unit
    #         read_only_fields = ['__all__']
    name = CharField(label='姓名')
    id_number = CharField(label='身份证号码(必填唯一)')
    phone = CharField(required=False, label='联系电话')
    status = IntegerField(required=False, label='人员状态，数字：1=参工2=待工-1=离职')
    ascription = IntegerField(required=False, label='归属劳务单位，数字：1=比选+短名单2=综合劳务3=招募+二次甄选')
    labor_service_unit = IntegerField(label='劳务单位unit_id，数字，填劳务单位对应的unit_id')
    team_attribute = IntegerField(required=False, label='队伍属性，数字:1=架子队+短名单2=市州工程队3=区县工程队4=劳务单位施工队')
    certificate_holding = JSONField(required=False, label='持证情况，格式（半角英文）：如[1,2],1=登高证2=电工证3=安全员证4=其它证')
    contract_signing_begin_date = DateField(required=False, label='与劳务单位合同签订日期，格式：年-月-日，如：\'2022-02-21(前面要加半角单引号\'，下同)')
    contract_signing_end_date = DateField(required=False, label='与劳务单位合同截止日期，格式：年-月-日，如：2022-08-21')
    insurance_limit = FloatField(required=False, label='保险额度（万元），数字:如100')
    insurance_effective_date = DateField(required=False, label='保险购买生效日，格式：年-月-日，如：2022-02-21')
    insurance_invalid_date = DateField(required=False, label='保险购买失效日，格式：年-月-日，如：2022-08-21')
    is_safety_responsibility = BooleanField(required=False, label='与劳务单位安全责任书签订，数字：1=已签订,0=未签订')
    project_name = CharField(required=False, label='实施项目名称')
    is_safety_education = BooleanField(required=False, label='上岗前的安全教育培训及考核，数字：1=已培训考核合格,0=未组织培训考核')
    is_monthly_safety_education = BooleanField(required=False, label='月度安全教育培训，数字：1=已组织,0=未组织')
    is_service_order = BooleanField(required=False, label='服务订单工单派发，数字：1=已派发,0=未派发')
    is_task_dispatch = BooleanField(required=False, label='任务单派发，数字：1=已派发,0=未派发')
    is_safety_disclosure = BooleanField(required=False, label='项目启动安全技术交底，数字：1=已组织,0=未组织')
    other_conditions = CharField(required=False, label='其他需要说明的情况')
    construction_contract_pdf = IntegerField(required=False, label='合同附件pdf_id，数字，填合同附件对应的pdf_id')
    insurance_pdf = IntegerField(required=False, label='保险附件pdf_id，数字，填保险附件对应的pdf_id')
    safety_responsibility_pdf = IntegerField(required=False, label='安全责任书附件pdf_id，数字，填安全责任书附件对应的pdf_id')
    safety_education_pdf = IntegerField(required=False, label='岗前教育培训附件pdf_id，数字，填岗前教育培训附件对应的pdf_id')
    safety_disclosure_pdf = IntegerField(required=False, label='项目启动前的安全技术交底附件pdf_id，数字，填项目启动前的安全技术交底附件对应的pdf_id')
    service_order_pdf = IntegerField(required=False, label='服务订单工单附件pdf_id，数字，填服务订单工单附件对应的pdf_id')
    task_dispatch_pdf = IntegerField(required=False, label='任务单附件pdf_id，数字，填任务单附件对应的pdf_id')
    class Meta:
        model = Opoc_Records
        fields = [
            'name','id_number','phone','status',
            'ascription',
            'labor_service_unit',
            'team_attribute',
            'certificate_holding',
            'contract_signing_begin_date',
            'contract_signing_end_date',
            'insurance_limit',
            'insurance_effective_date',
            'insurance_invalid_date',
            'is_safety_responsibility','project_name','is_safety_education',
            'is_monthly_safety_education','is_service_order','is_task_dispatch','is_safety_disclosure',
            'other_conditions',
            'construction_contract_pdf',
            'insurance_pdf','safety_responsibility_pdf',
            'safety_education_pdf','safety_disclosure_pdf','service_order_pdf','task_dispatch_pdf',
        ]

    def validate_status(self, value):
        if value_is_in_arr(value,[0,1,-1])==False:
            raise ValidationError('人员状态' + str(value) + '不在[0,1,-1]范围内')
        return value

    def validate_id_number(self, value):
        res =checkIdcard(value)
        if res!=True:
            raise ValidationError(value+"身份证号码格式不对")
        return value

    def validate_phone(self, value):
        res = re.match(r'1[3,4,5,7,8,9]\d{9}', value)
        if re.match(r'1[3,4,5,7,8,9]\d{9}',value) is None:
            raise ValidationError(value + '手机号码格式不对')
        return value


class Opoc_Certificate_ImgsSerializer(BaseSerializer):
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    class Meta:
        model = Opoc_Certificate_Imgs
        read_only_fields = ['id', 'name','type',
                            'filled_by','filled_by_name','add_time']
        fields = ['file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        validated_data['type'] = self.request.data['type']
        validated_data['filled_by'] = self.user
        return super().create(validated_data)


class Opoc_Common_PdfsSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    class Meta:
        model = Common_Pdfs
        read_only_fields = ['id', 'company','company_name','name','type',
                            'filled_by','filled_by_name','add_time']
        fields = ['file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        validated_data['company'] = self.user.company
        validated_data['type'] = self.request.data['type']
        validated_data['filled_by'] = self.user
        return super().create(validated_data)


class Opoc_InspectionPhotosSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    class Meta:
        model = Opoc_InspectionPhoto
        read_only_fields = ['id', 'company','company_name','name',
                            'filled_by','filled_by_name','add_time']
        fields = ['file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        validated_data['company'] = self.user.company
        validated_data['filled_by'] = self.user
        return super().create(validated_data)


class Opoc_InspectionRecordsSerializer(BaseSerializer):
    company = CharField(source='opoc_record.company', read_only=True, label='公司')
    company_name = CharField(source='opoc_record.company.name', read_only=True, label='公司名')
    opoc_record_name = CharField(source='opoc_record.name',  read_only=True, label='被检查人')
    inspector_name = CharField(source='inspector.name',  read_only=True, label='检查人')
    opoc_InspectionPhotos=Opoc_InspectionPhotosSerializer(source='photos', many=True, read_only=True, label='检查照片')

    class Meta:
        model = Opoc_InspectionRecord
        read_only_fields = ['id', 'company','company_name','inspector_name','inspector_name','opoc_record_name','created_at','opoc_InspectionPhotos']
        fields = [
            'inspection_time',
            'inspection_location',
            'description',
            'opoc_record',
            'photos',
            'inspector',
            *read_only_fields
        ]

    def create(self, validated_data):
        validated_data['inspector'] = self.user
        return super().create(validated_data)



class Opoc_Labor_service_unitsSerializer(BaseSerializer):
    slug = serializers.SlugField(default=serializers.CreateOnlyDefault(''))
    # id = serializers.SerializerMethodField()
    company_name = CharField(source='company.name', read_only=True, label='公司')
    filled_by_name = CharField(source='filled_by.name',  read_only=True, label='填报人')
    class Meta:
        model = Labor_service_unit
        read_only_fields = ['id','slug','company_name',
                            'filled_by_name','add_time']
        fields = '__all__'

    def get_id(self, instance):
        return str(uuid.UUID(instance.id)).upper()

    # def create(self, validated_data):
    #     instance = super().create(validated_data)
    #     instance.id = uuid.UUID(instance.id).hex
    #     instance.save()
    #     return instance

    # def update(self, instance, validated_data):
    #     instance = super().update(instance, validated_data)
    #     instance.id = uuid.UUID(instance.id).hex
    #     instance.save()
    #     return instance
    # def get_id(self, obj):
    #     return str(obj.id).replace('-', '')



class Labor_service_unitImportExportSerializer(BaseSerializer):
    name = CharField(label='劳务单位名称(必填唯一)')
    class Meta:
        model = Labor_service_unit
        fields = ['name']




__all__ = [
    'Opoc_RecordsSerializer',
    'Opoc_Common_PdfsSerializer',
    'Opoc_Labor_service_unitsSerializer',
    'Labor_service_unitImportExportSerializer',
    'Opoc_Certificate_ImgsSerializer',
    'Opoc_RecordsImportSerializer',
]